<template>
  <view class="body">
    <view class="header-title">{{
      status ? '账号密码登录' : '手机验证码登录'
    }}</view>
    <!-- 账号密码登录 -->
    <template v-if="status">
      <view class="login-input-box"
        ><input
          @input="usernameInput"
          placeholder="请输入账号"
          placeholder-style="color:#c0c4cc"
		  :value="username"
		  @focus="getInputHistory"
		  @blur="hiddenSelect"
      /></view>
	  <scroll-view v-if="matchSource.length>0 && isShow" :scroll-y="true" class="sunui-select-dropdown">
	  	<view class="sunui-scrollbar">
	  		<view class="sunui-select-dropdown__wrap">
	  			<!-- 这里可以DIY文字颜色 -->
	  			<view  v-for="(item,index) in matchSource" :key='index'>
	  				<view :id="item" @tap="selectedVal" class="sunui-autofill-item">{{item}}</view>
	  			</view>
	  		</view>
	  	</view>
	  </scroll-view>
      <view class="login-input-box">
        <input
          :password="defaultType"
          @input="passwordInput"
          placeholder="请输入密码"
          placeholder-style="color:#c0c4cc"
        />
        <view class="eye-pwd u-f-ajc" @click="showPassword">
          <view class="u-f-ajc"
            ><u-icon :name="defaultType ? 'eye-fill' : 'eye-off'"></u-icon
          ></view>
        </view>
      </view>
    </template>
    <!-- 手机验证码登录 -->
    <template v-else>
      <view class="login-input-box">
        <view class="phone u-f-ajc login-font-color">
          +86
          <u-icon name="arrow-right"></u-icon>
        </view>
        <input
          type="number"
          class="phone-input"
          @input="phoneInput"
          placeholder="请输入您的手机号"
          placeholder-style="color:#c0c4cc"
        />
      </view>
      <view class="login-input-box">
        <input
          type="number"
          @input="checknumInput"
          placeholder="请输入验证码"
          placeholder-style="color:#c0c4cc"
        />
        <view
          class="send-code u-f-ajc login-font-color yanzhengma"
          @tap="getCheckNum"
        >
          <view class="u-f-ajc">{{
            !codetime ? '发送验证码' : codetime + 'S'
          }}</view>
        </view>
      </view>
    </template>
    <view class="register-forget u-f-ajc u-f-row u-f-jsb">
      <text @click="register">新用户注册</text>
      <text @click="forget">忘记密码</text>
    </view>
    <button
      class="user-set-btn"
      :class="{ 'user-set-btn-disable': disabled }"
      type="primary"
      :loading="loading"
      @click="loginSubmit"
      :disabled="disabled"
    >
      登录
    </button>
    <!-- 登录状态切换 -->
    <view class="login-status login-font-color u-f-ajc">
      <text @tap="changeStatus">{{
        status ? '验证码登录' : '账号密码登录'
      }}</text>
      <u-icon name="arrow-right"></u-icon>
    </view>
    <!-- 第三方登陆 -->
    <view class="other-login-title u-f-ajc" style="padding: 50upx 0;"
      >使用第三方账号登录</view
    >
    <view class="other-login u-f-ajc">
      <button
        type="default"
        open-type="getUserInfo"
        @getuserinfo="getUserInfo"
        withCredentials="true"
      >
        <image
          src="../../static/image/wx-login.png"
          @tap="authorization"
        ></image>
      </button>
    </view>
    <u-popup border-radius="10" v-model="show" mode="bottom" length="60%">
      <u-cell-group title="轻触切换账号"></u-cell-group>
      <view class="cardRow" v-for="(item, index) in loginInfoArr" :key="index">
        <view
          class="cardBox"
          @tap="selectAccount(item.token, item.userInfo,item.userRole)"
          style="display: flex;"
        >
          <image
            class="leftImg"
            :src="getImgUrl(item.userInfo.avatar)"
            mode="aspectFill"
          ></image>
          <view style="display: flex; padding-left: 22rpx;" class="u-f-column">
            <text>帐号：{{ item.userInfo.username }}</text>
            <text>姓名:{{ item.userInfo.name }}</text>
            <text>手机号：{{ item.userInfo.mobile }}</text>
          </view>
        </view>
        <u-line color="#e4e7ed" />
      </view>
    </u-popup>
  </view>
</template>

<script>
import md5 from '../../common/md5.js'
import { FactoryInfoMixin,sFactoryInfoMixin, SendCodeMixin } from '../../mixins/loginMixins.js'
export default {
  mixins: [FactoryInfoMixin,sFactoryInfoMixin, SendCodeMixin],
  data() {
    return {
      show: false,
      loading: false,
      status: true, //true代表账号密码登录，false代表手机验证码登录
      disabled: true,
      defaultType: true,
      username: '',
      password: '',
      phone: '',
      checknum: '',
      loginInfoArr: [],
	  isShow:false,
	  matchSource: [],
    }
  },
  onLoad() {
	  uni.hideHomeButton()
  },
  onShow() {
  	console.log('login onShow')
  	let history = uni.getStorageSync('history')
  	if(history){
  		 this.matchSource=uni.getStorageSync('history')
  		 console.log(this.matchSource)
  	}
  },
  methods: {
	  //选择历史记录的账号
	  selectedVal(e) {
	  	this.username = e.target.id;
	  	this.isShow = false
	  },
	  //获取历史记录
	  getInputHistory(event){
		  this.isShow = true
	  },
	  //失去焦点隐藏Select框
	  hiddenSelect(){
		  this.isShow = false
	  },
    //监听输入的账号
    usernameInput(event) {
      this.username = event.detail.value
      this.OnBtnChange()
    },
    //监听输入的密码
    passwordInput(event) {
      this.password = event.detail.value
      this.OnBtnChange()
    },
    //监听输入的手机号
    phoneInput(event) {
      this.phone = event.detail.value
      this.OnBtnChange()
    },
    //监听输入的验证码
    checknumInput(event) {
      this.checknum = event.detail.value
      this.OnBtnChange()
    },
    // 初始化表单
    initInput() {
      this.username = ''
      this.password = ''
      this.phone = ''
      this.checknum = ''
    },
    // 改变按钮状态
    OnBtnChange() {
      if ((this.username && this.password) || (this.phone && this.checknum)) {
        this.disabled = false
        return
      }
      this.disabled = true
    },
    //显示密码或者隐藏密码
    showPassword() {
      this.defaultType = !this.defaultType
    },
    selectAccount(token, userinfo,userRole) {
      uni.setStorageSync('token', token)
      uni.setStorageSync('userInfo', userinfo)
	  if(userRole === 'sfactory'){
		  uni.setStorageSync('clientId', 'sfactory_wxa')
		  this.sfactoryUserInfo()
	  }else {
	  //引入判断审核状态的方法
		this.currentFactoryInfo()
	  }
      this.show = false
    },
    getImgUrl(img) {
      return 'http://files.ybangy.net/' + img
    },
    // 获取验证码
    getCheckNum() {
      //引入发送验证码方法
      this.sendCodeUtil(this.phone, '1')
    },
    // 切换登录状态
    changeStatus() {
      this.initInput()
      this.status = !this.status
    },
    //注册账号
    register() {
      uni.navigateTo({
        url: '../login/register',
      })
    },
    //忘记密码
    forget() {
      uni.navigateTo({
        url: '../login/forget',
      })
    },
    //登录
    loginSubmit() {
      uni.setStorageSync('clientId', '_wxa')
      uni.removeStorageSync('token')
      if (this.status) {
        let loginparams = {
          username: this.username,
          password: md5.hex_md5(this.password),
        }
        this.$store.dispatch('userLogin', loginparams).then((res) => {
          if (res.data.errorCode === 0) {
            uni.removeStorageSync('clientId')
			if(res.data.data.userRole === 'sfactory'){
				uni.setStorageSync('clientId', 'sfactory_wxa')
				this.sfactoryUserInfo()
			}else{
				//引入判断审核状态的方法
				this.currentFactoryInfo()
			}
			let historyArr  = []
			historyArr.push(this.username)
			let filterArr =  uni.getStorageSync('history') ? uni.getStorageSync('history').concat(historyArr): historyArr
			 let newArr = filterArr.filter(item => item)
			 let storageHistory =  Array.from(new Set(newArr))
			uni.setStorageSync('history',storageHistory)
          }
        })
      } else {
        let loginparams = {
          tel: this.phone,
          captcha: this.checknum,
        }
        this.$store.dispatch('telLogin', loginparams).then((res) => {
          if (res.data.errorCode === 0) {
            uni.removeStorageSync('clientId')
			if(res.data.data.userRole === 'sfactory'){
				uni.setStorageSync('clientId', 'sfactory_wxa')
				this.sfactoryUserInfo()
			}else {
				//引入判断审核状态的方法
				this.currentFactoryInfo()
			}
          }
        })
      }
    },
    //微信授权登录
    getUserInfo() {
      uni.setStorageSync('clientId', '_wxa')
      uni.removeStorageSync('token')
      let that = this
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          console.log(loginRes)
          let js_code = loginRes.code //js_code可以给后台获取unionID或openID作为用户标识
          uni.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session', //仅为示例，并非真实接口地址。
            data: {
              appid: 'wxa2341e1f89fcd33a',
              secret: 'aceec9d42f9bb76c32a2a1b693597386',
              js_code: js_code,
              grant_type: 'authorization_code',
            },
            header: {
              'content-type': 'application/json', //默认值
            },
            success: (res) => {
              let SESSION_KEY = res.data.session_key //获取到session_key
              uni.getUserInfo({
                provider: 'weixin',
                success: function (infoRes) {
                  let encrypted = {
                    mobile: infoRes.encryptedData,
                    iv: infoRes.iv,
                    sessionKey: SESSION_KEY,
                  }
                  that.$store.dispatch('decryptData', encrypted).then((res) => {
                    let unionId = res.data.data.unionId
                    that.$store
                      .dispatch('wxLogin', { unionid: unionId })
                      .then((ret) => {
                        if (ret.data.errorCode === 0) {
                          uni.removeStorageSync('clientId')
                          that.loginInfoArr = ret.data.data.filter((item) => {
							  if(item.userRole === 'factory'){
								  return item.userRole === 'factory'
							  }else if(item.userRole === 'sfactory'){
								   return item.userRole === 'sfactory'
							  }
                          })
                          that.show = true
                        }
                      })
                  })
                },
                fail: function () {
                  uni.showModal({
                    title: '温馨提示',
                    content:
                      '您点击了拒绝授权,将无法正常使用小程序,点击"授权"按钮并允许使用"用户信息"方可正常使用。',
                    confirmText: '授权',
                    success: (res) => {
                      if (res.confirm) {
                        wx.openSetting({
                          success: (res) => {},
                        })
                      }
                    },
                  })
                },
              })
            },
          })
        },
      })
    },
  },
}
</script>

<style lang="scss">
page {
  background: #fff;
}
phone-code-extend {
  position: absolute;
  top: 0;
  height: 100%;
  z-index: 100;
}
.login-font-color {
  color: #5880ff;
}
.body {
  padding: 0 30upx !important;
  .header-title {
    margin-top: 40upx;
    font-size: 55upx;
    font-weight: 700;
    line-height: 130upx;
  }
  .login-input-box {
    position: relative;
    font-size: 30upx;
    border-bottom: 1upx solid #f4f4f4;
    input {
      height: 2.2rem;
      font-size: 34upx !important;
    }
    .phone-input {
      padding-left: 100upx;
    }
    .eye-pwd {
      @extend phone-code-extend;
      width: 60upx;
      right: 0;
    }
    .phone {
      @extend phone-code-extend;
      width: 100upx;
      left: 0;
      font-weight: bold;
    }
    .send-code {
      @extend phone-code-extend;
      width: 150upx;
      right: 0;
    }
    .yanzhengma view {
      background: #eeeeee;
      border-radius: 10upx;
      font-size: 25upx;
      width: 150upx;
      padding: 10upx 0;
    }
  }
  .login-input-box:nth-child(2) {
    margin: 80upx 0;
  }
  .register-forget {
    padding: 40upx 0;
    font-size: 30upx;
    color: #999999;
  }
  .login-status {
    padding: 40upx 0;
    font-size: 32upx;
  }
  .other-login-title {
    position: relative;
    color: #999999;
    font-size: 30upx;
    font-weight: 400;
    &::before {
      content: '';
      position: absolute;
      background: #bbbbbb;
      height: 2upx;
      width: 22%;
      top: 50%;
      left: 5%;
    }
    &::after {
      content: '';
      position: absolute;
      background: #bbbbbb;
      height: 2upx;
      width: 22%;
      top: 50%;
      right: 5%;
    }
  }
  .other-login {
    padding: 20upx 80upx;
    button {
      background-color: #ffffff;
      image {
        width: 110rpx;
        height: 110rpx;
      }
      &::after {
        border: none !important;
      }
    }
  }
  .cardRow {
    .cardBox {
      position: relative;
      padding: 15upx 30upx;
      .leftImg {
        width: 100upx;
        height: 100upx;
      }
      u-icon {
        position: absolute;
        right: 22px;
        top: 24px;
      }
    }
  }
}
</style>
<style>
	.sunui-select-dropdown{
		width: 222px;

		z-index: 2013;
		position: absolute;
		top: 156px;
		margin-top: 4px;
		border: 1px solid #E4E7ED;
		border-radius: 4px;
		background-color: #FFF;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
	}
	.sunui-scrollbar{
		overflow: hidden;
		/* height: 20vh; */
	}
	.sunui-select-dropdown__wrap{
		overflow: scroll;
		height: 100%;
	}
	
	.sunui-autofill-item{
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-size: 15px;
		padding: 0 10rpx;
		color: #606266;
		height: 58rpx;
		line-height: 58rpx;
	}
	.sunui-autofill-item:hover{
		background-color: #F5F7FA;
	}
</style>